import { Component, Vue } from 'vue-property-decorator';

@Component
export default class StreamHandler extends Vue {
  private buffer = '';
  private controller: AbortController | null = null;
  private lastChunk;
  // 发起流式请求
  async fetchStream(prompt: string) {
    this.controller = new AbortController();
    
    try {
        const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${process.env.VUE_APP_DEEPSEEK_KEY}`
        },
        body: JSON.stringify({
          model: "deepseek-chat",
          messages: [{ role: "user", content: prompt }],
          stream: true,
          temperature: 0.7,
          max_tokens: 4000
        }),
        signal: this.controller.signal
      });

      await this.processStream(response);
    } catch (err) {
      if (err.name !== 'AbortError') {
        this.$emit('stream-error', err);
      }
    }
  }

  private processBuffer(final = false) {
    const lines = this.buffer.split('\n');
    this.buffer = lines.pop() || ''; // 保留未完成数据
  
    lines.forEach(line => {
      if (!line.startsWith('data: ')) return;
      try {
        const data = JSON.parse(line.slice(6));
        const content = data.choices[0]?.delta?.content || '';
        // 添加去重校验
        if (content && content !== this.lastChunk) {
          this.$emit('stream-data', content);
          this.lastChunk = content;
        }
      } catch (err) {
        console.warn('解析JSON失败:', line);
      }
    });
  }

  // 处理数据流
  private async processStream(response: Response) {
    const reader = response.body?.getReader();
    const decoder = new TextDecoder();

    if (!reader) return;
    let shouldContinue = true
    while (shouldContinue) {
      const { done, value } = await reader.read();
      if (done) {
        shouldContinue = false 
        break;
      }
    

      this.buffer += decoder.decode(value, { stream: true });
      this.processBuffer();
    }
    this.processBuffer(true); // 处理最后剩余数据
  }

  // 终止流
  abortStream() {
    this.controller?.abort();
    this.buffer = '';
  }
}